package com.example.test2.main.fragment;

import android.content.Intent;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.example.test2.R;
import com.example.test2.activity.AddNewsActivity;
import com.example.test2.activity.NewsActivity;
import com.example.test2.adapter.LocalNewSAdapter;
import com.example.test2.adapter.NewSAdapter;
import com.example.test2.databinding.FragmentNewsBinding;
import com.example.test2.db.control.NewsDbController;
import com.example.test2.db.entity.New;
import com.example.test2.event.NewEvent;
import com.example.test2.http.Constants;
import com.example.test2.http.OkHttpUtil;
import com.example.test2.http.bean.News;
import com.example.test2.utils.Tools;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class NewsFragment extends BaseFragment<FragmentNewsBinding> {

    @Override
    protected void initData() {
        super.initData();
        Tools.setStatusBarColor(getActivity(), R.color.bg_title);
        EventBus.getDefault().register(this);
        dbNewsDbController = NewsDbController.getInstance(getActivity());
        sendRequest("top");
        initLocal("0");
        initIndicator();
    }

    @Override
    protected void initClick() {
        super.initClick();
        getBinding().ivAdd.setOnClickListener(view -> {
            startActivity(new Intent(getActivity(), AddNewsActivity.class));
        });
    }

    @Override
    protected int initLayout() {
        return R.layout.fragment_news;
    }

    private void initIndicator() {

        getBinding().indicatorView.setOnIndicatorChangedListener((oldSelectedIndex, newSelectedIndex) -> {
            switch (newSelectedIndex) {//0-3
                case 0:
                    sendRequest("top");
                    initLocal("0");
                    break;
                case 1:
                    sendRequest("nongye");
                    initLocal("1");
                    break;
                case 2:
                    sendRequest("tiyu");
                    initLocal("2");
                    break;
                case 3:
                    sendRequest("caijing");
                    initLocal("3");
                    break;
            }
        });
    }


    List<New> list = new ArrayList<>();
    private LocalNewSAdapter newSAdapter2;
    private NewsDbController dbNewsDbController;

    private void initLocal(String type) {//本地新闻适配器

        if (type.equals("0")) {
            list = dbNewsDbController.searchAll();
        } else {
            list = dbNewsDbController.searchByWhere(type);
        }

        if (newSAdapter2 == null) {
            newSAdapter2 = new LocalNewSAdapter(getActivity(), list);
            getBinding().rvData2.setLayoutManager(new LinearLayoutManager(getActivity(),
                    LinearLayoutManager.VERTICAL, false));
            getBinding().rvData2.setAdapter(newSAdapter2);
        } else {
            newSAdapter2.setList(list);
            newSAdapter2.notifyDataSetChanged();
        }

        newSAdapter2.setListener(pos -> {
            Intent intent = new Intent(getContext(), NewsActivity.class);
            intent.putExtra("data", list.get(pos));
            intent.putExtra("add", true);
            startActivity(intent);
        });
    }

    private void sendRequest(String type) {

        OkHttpUtil.sendHttpRequest(Constants.JUHE_URL + "?type=" + type + "&key=" + Constants.JUHE_KEY, new Callback() {
            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                if (response.isSuccessful()) {
                    String responseBody = response.body().string();

                    Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
                    News news = gson.fromJson(responseBody, News.class);

                    if (news.getReason().contains("超过每日可允许请求次数!")) {
                        handler.sendEmptyMessage(0);
                        return;
                    }
                    if (news.getResult() != null) {
                        newList.clear();
                        newList.addAll(news.getResult().getData());
                        handler.sendEmptyMessage(1);
                    }
                }
            }

            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                e.printStackTrace();
            }
        });
    }


    List<News.Result.Data> newList = new ArrayList<>();
    private NewSAdapter newSAdapter;

    private void initAdapter() {

        if (newSAdapter == null) {
            newSAdapter = new NewSAdapter(getActivity(), newList);
            getBinding().rvData.setLayoutManager(new LinearLayoutManager(getActivity(),
                    LinearLayoutManager.VERTICAL, false));
            getBinding().rvData.setAdapter(newSAdapter);
        } else {
            newSAdapter.setList(newList);
            newSAdapter.notifyDataSetChanged();
        }

        newSAdapter.setListener(pos -> {
            Intent intent = new Intent(getContext(), NewsActivity.class);
            intent.putExtra("data", newList.get(pos));
            startActivity(intent);
        });
    }

    Handler handler = new Handler(msg -> {
        switch (msg.what) {
            case 0:
                Toast.makeText(getActivity(), "超过每日可允许请求次数!", Toast.LENGTH_SHORT).show();
                break;
            case 1:
                initAdapter();
                break;
        }
        return false;
    });

    @Override
    protected FragmentNewsBinding onCreateViewBinding(@NonNull LayoutInflater inflater, @Nullable ViewGroup parent) {
        return FragmentNewsBinding.inflate(inflater, parent, false);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGetMessage(NewEvent event) {
        getBinding().indicatorView.setIndex(0);
        list = NewsDbController.getInstance(getActivity()).searchAll();
        initLocal("0");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}